package cn.migu.music.hangupsms.cachemanage.handler;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import cn.migu.music.common.utils.LogUtils;
import cn.migu.music.hangupsms.cachemanage.event.AbsCacheEvent;
import cn.migu.music.hangupsms.cachemanage.event.EventConstants;
import cn.migu.music.hangupsms.common.config.HangUpSmsDbConfig;
import cn.migu.music.hangupsms.common.entity.SmsProvinceSwitchSettings;
import cn.migu.music.hangupsms.repository.SmsProvinceSwitchSettingsMapper;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class SmsSendProvinceCacheHandler extends AbsCacheHandler<AbsCacheEvent> {
    @Autowired
    private SmsProvinceSwitchSettingsMapper smsProvinceSwitchSettingsMapper;
    @Autowired
    private HangUpSmsDbConfig               hangUpSmsDbConfig;

    @PostConstruct
    @Override
    public void init() {
        reload(EventConstants.SMS_SEND_PROVINCE_CHANGED_EVENT);
    }

    @Override
    public void reload(AbsCacheEvent cacheEvent) {
        List<SmsProvinceSwitchSettings> provinceSwitchSettingsList = null;
        try {
            provinceSwitchSettingsList = smsProvinceSwitchSettingsMapper.getAllSettings();
        } catch (Exception e) {
            LogUtils.error(e, log, "get data error");
        }
        if (CollectionUtils.isEmpty(provinceSwitchSettingsList)) {
            return;
        }
        StringBuilder noSendSmsProvinceId = new StringBuilder();
        for (SmsProvinceSwitchSettings settings : provinceSwitchSettingsList) {
            if (settings.getApplyStatus() == null || settings.getApplyStatus() == 0) {
                continue;
            }
            if (settings.getSwitchOn() == 0) {
                noSendSmsProvinceId.append(settings.getProvinceId()).append("|");
            }
        }
        if (noSendSmsProvinceId.length() > 0) {
            noSendSmsProvinceId = new StringBuilder(noSendSmsProvinceId.substring(0, noSendSmsProvinceId.length() - 1));
        }
        hangUpSmsDbConfig.setCallerNoSendProvinceIds(noSendSmsProvinceId.toString());
    }
}
